import axios from 'axios'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
import { getToken } from '@/utils/auth'
import {getDownloadUrl} from "@/api/pms/download";

const mimeMap = {
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  zip: 'application/zip'
}

const baseUrl = process.env.VUE_APP_BASE_API
export function downLoadZip(str, filename) {
  var url = baseUrl + str
  axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: { 'Authorization': 'Bearer ' + getToken() }
  }).then(res => {
    resolveBlob(res, mimeMap.zip)
  })
}
/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {String} mimeType MIME类型
 */
export function resolveBlob(res, mimeType) {
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], { type: mimeType })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var contentDisposition = decodeURI(res.headers['content-disposition'])
  var result = patt.exec(contentDisposition)
  var fileName = result[1]
  fileName = fileName.replace(/\"/g, '')
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  // document.body.appendChild(aLink)
  aLink.click()
  // document.body.appendChild(aLink)
}


const getFile = url => {
  return new Promise((resolve, reject) => {
    axios({
      method: 'get',
      url,
      headers: {'Authorization': 'Bearer ' + getToken()},
      responseType: 'arraybuffer'
    }).then(data => {
      resolve(data.data)
    }).catch(error => {
      reject(error.toString())
    })
  })
}

export const handleBatchDownload = (fileList,docname=null,docid,root) => {
  //const data = ['各类地址1', '各类地址2'] // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
  const zip = new JSZip()
  const cache = {}
  const promises = []
  root.progress.open = true
  var index = 0;
  var error = 0;
  fileList.forEach(item => {
    if(item.path && error===0){
      /**文件下载*/
      if(item.path!==''){
        var downloadUrl = "http://"+ window.location.host + item.path;
        const promise = getFile(downloadUrl).then(data => { // 下载文件, 并存成ArrayBuffer对象
          const arr_name = item.path.split("/")
          const file_name = cache[item.fileName] ? item.fileName.split('.')[0]+'(1).'+item.fileName.split('.')[1]: item.fileName // 获取文件名
          zip.file(file_name, data, { binary: true }) // 逐个添加文件
          root.progress.percent = parseInt((++index)*100/fileList.length)
          cache[file_name] = data
        })
        promises.push(promise)
      }else{
        error=1;
      }
      /**文件下载*/
      /**S3文件下载
      var num = item.path.lastIndexOf("/");
      var bucket = item.path.substring(0, num);
      var downloadName = item.fileName;
      getDownloadUrl(bucket,downloadName,item.docId).then(response=> {
        if(response.url!==''){
          var downloadUrl = "http://"+window.location.host+response.url
          const promise = getFile(downloadUrl,).then(data => { // 下载文件, 并存成ArrayBuffer对象
            const arr_name = item.path.split("/")
            const file_name = cache[item.fileName] ? item.fileName.split('.')[0]+'(1).'+item.fileName.split('.')[1]: item.fileName // 获取文件名
            zip.file(file_name, data, { binary: true }) // 逐个添加文件
            root.progress.percent = parseInt((++index)*100/fileList.length)
            cache[file_name] = data
          })
          promises.push(promise)
        }else{
          error=1;
        }
      });
       /**S3文件下载*/
    }
  });
  setTimeout(()=>{
    var timestamp = Date.parse(new Date())/1000;
    console.log(promises);
    if(promises){
      Promise.all(promises).then(() => {
        zip.generateAsync({ type: "blob" }).then(content => { // 生成二进制流
          FileSaver.saveAs(content, docname+timestamp+".zip") // 利用file-saver保存文件
          root.progress.open = false
        });
      })
    }
  },3000);
}
